package cn.edu.lcu.cs.javaweb.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.UUID;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(urlPatterns = { "/upload" }, initParams = {
		@WebInitParam(name = "uploadFolder", value = "D:\\temp", description = "文件上传的保存路径") })
// 若想让Servlet从请求数据流中解析上传的文件，需要加一个Servlet3.x标准文件上传功能的注解
@MultipartConfig(maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 100)
public class UploadServlet extends HttpServlet {
	private String uploadFolder;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		uploadFolder = config.getInitParameter("uploadFolder");
		// 判断文件夹是否存在，如果不存在就创建它
		File folder = new File(uploadFolder); // 文件夹是一种特殊的文件
		if (!folder.exists()) {
			// 如果文件夹不存在，就创建它
			folder.mkdirs();
		}
	}
	
	public UploadServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// /upload --> /upload.jsp
		request.getRequestDispatcher("/upload.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		
		writer.write("<br>nickname is " + request.getParameter("nickname"));
		
		// 从请求对象中获取所有上传的Part，包含文件Part与普通上传参数Part
		Collection<Part> parts = request.getParts();
		// 遍历Parts，将其中的文件写入本地磁盘文件系统
		for (Part part : parts) {
			// if (part.getName().equals("avator")) {
			if (part.getContentType() != null){ // 如果上传的是文件，contenttype非空
//				System.out.println(part.getContentType());
				// 获取原始文件名
				String filename = part.getSubmittedFileName();
				// 获取文件的扩展名
				filename = filename.substring(filename.lastIndexOf('.'));
				filename = uploadFolder + File.separator + UUID.randomUUID() + filename;
				part.write(filename);	// d:\temp \ uuid.jpg
				writer.write("<br>文件上传成功：" + filename);
			}
		}
	}
	
}
